package com.kitty.game.gm.handler;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.gm.GmService;
import com.kitty.game.role.model.Role;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.RoleNameChangeEvent;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;

public class GmName implements GMFather {
    @Override
    public boolean handle(Role aaa, String content) {
        content = SpringUtils.getBean(GmService.class).replaceName(content);
        content = content.trim();
        String[] strings = content.split("##");
        int count = SpringUtils.getBean(Dao.class).count(Role.class, Cnd.where("name", "=", strings[1]));
        if (count > 0) {
            MessagePusher.pushMessage(aaa, new RespNotifyMiscEx("角色名称已经存在，请重新选择角色名！"));
            return true;
        }
        Role temp = SpringUtils.getBean(Dao.class).fetch(Role.class, Cnd.where("roleId", "=", Integer.parseInt(strings[0])));
        if (temp == null) {
            MessagePusher.pushMessage(aaa, new RespNotifyMiscEx("角色ID不存在！"));
            return true;
        }
        // 内存中是否有这个角色
        Role role = SpringUtils.getPlayerService().getPlayerBy(temp.getUid());
        if (role != null) {
            temp = role;
        }
        String oldName = temp.getName();
        temp.setName(strings[1]);
        temp.save();
        // 让玩家重上
        SpringUtils.getPlayerService().updateRoleName(oldName, temp);
        EventDispatcher.getInstance().fireEvent(new RoleNameChangeEvent(EventType.ROLE_NAME_CHANGE, temp, oldName, strings[1]));
        IoSession session = SessionUtils.getSessionBy(temp.getUid());
        if (session != null) {
            session.closeNow();
        }
        return true;
    }
}
